import { createRouter, createWebHistory } from 'vue-router'
import store from '../store'
import CheckInRecord from '../views/CheckInRecord.vue'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/LoginView.vue'),
    meta: { title: '登录', guest: true }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/RegisterView.vue'),
    meta: { title: '注册', guest: true }
  },
  {
    path: '/forgot-password',
    name: 'ForgotPassword',
    component: () => import('../views/ForgotPassword.vue'),
    meta: { title: '找回密码', guest: true }
  },
  {
    path: '/home',
    name: 'Home',
    component: () => import('../views/Home.vue'),
    meta: { title: '首页' }
  },
  {
    path: '/plan-list',
    name: 'PlanList',
    component: () => import('../views/PlanList.vue'),
    meta: { title: '打卡计划列表' }
  },
  {
    path: '/plan-create',
    name: 'PlanCreate',
    component: () => import('../views/PlanCreate.vue'),
    meta: { title: '新建计划' }
  },
  {
    path: '/plan-detail/:id',
    name: 'PlanDetail',
    component: () => import('../views/PlanDetail.vue'),
    meta: { title: '计划详情' }
  },
  {
    path: '/check-in/:id',
    name: 'CheckIn',
    component: () => import('../views/CheckIn.vue'),
    meta: { title: '打卡操作' }
  },
  {
    path: '/check-in-record',
    name: 'CheckInRecord',
    component: CheckInRecord,
    meta: {
      title: '打卡记录',
      requiresAuth: true
    }
  },
  {
    path: '/profile',
    name: 'Profile',
    component: () => import('../views/Profile.vue'),
    meta: {
      requiresAuth: true,
      layout: 'AppLayout'
    }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  document.title = to.meta.title || '打卡系统'
  const isAuthenticated = store.state.user.isAuthenticated

  if (to.meta.guest && isAuthenticated) {
    next('/home')
  } else if (!to.meta.guest && !isAuthenticated && to.path !== '/login') {
    next('/login')
  } else {
    next()
  }
})

export default router